/*
* @Author: zhaoxiaoyang
* @Date:   2021-08-25 12:17:00
* @Last Modified by:   zhaoxiaoyang
* @Last Modified time: 2021-08-25 13:02:00
*/
'use strict'

const fs = require('fs'),
      exists = fs.exists,
      packer = `./dist/package.json`,
      pkgStr = `{
        "name": "real-estate-marketplace-demonstrate",
        "version": "1.0.0",
        "description": "",
        "main": "index.html",
        "repository": "https://gitlab.com/frk2/realestatemarket.git",
        "author": "zhaoxiaoyang",
        "license": "MIT",
        "scripts": {
          "start": "http-server -c-1 -p8888"
        },
        "dependencies": {
          "http-server": "^0.12.3"
        }
      }`


let resetFilePath = path => {

  fs.readdir(path, (err, dir) => {
    if (err) {
      console.log('read dir err:', err)
      return
    }
    console.log('dir:', dir)
    dir.map(m => {
      fs.readFile(path + m, 'utf-8', function (err, data) {
        if(err) {
          console.error('read file err, curFolder:', m)
          resetFilePath(path + m + '/')
          return
        }
        if(/\.html$|\.css$|.js$/g.test(m)) {
          console.log('read ok:', path + m + '\n')
          data = 
                /html$|js$/.test(m) ? 
                data.replace(/=\/pre\/static\//g, '=/static/'):
                /css$/.test(m) ?
                data.replace(/url\(\/pre\/static\//g, 'url(/static/'):
                data
          fs.writeFile(path + m, data, 'utf-8', function (err, res) {
            // console.log('writeFile:', path, arguments)
            if (err) {
              console.log('write data error:', err, res)
              return
            }
            console.log(`this file "${m}" has been wrote.`)
          })
        }
      })
    })
  })
}

resetFilePath('./dist/')

exists(packer, (e) => {
    if (e) {
      console.error(`${packer} already exists.`)
    } else {
      fs.writeFile(packer, pkgStr, 'utf-8', function (err, res) {
        if(err) {
          console.log('write data error:', err, res)
          return
        }
        console.log('package.json saved.')
      })
      /*open(`${m}package.json`, 'wx', (err, fd) => {
        if (err) throw err
        try {
          // writeMyData(fd)
          console.log(fd)
        } finally {
          close(fd, (err) => {
            if (err) throw err
          })
        }
      })*/
    }
  })

module.exports = {
  NODE_ENV: '"local"'
}
